import React, { Component,} from 'react';
import ReactDOM from 'react-dom';
import ContentCard from '../contentCard/index'
import { PullToRefresh, ListView, Button,Toast } from 'antd-mobile';
import axios from "axios"
import { connect } from 'react-redux';
import { ContentAction } from '../../actions/content';

class TabbarBody extends Component {
    constructor(props) {
        super(props);
        const dataSource = new ListView.DataSource({
            rowHasChanged: (row1, row2) => row1 !== row2,
        });

        this.state = {
            dataSource,
            refreshing: true,
            isLoading: true,
            height: document.documentElement.clientHeight,
            useBodyScroll: false,
            pageNo: 1,
            pageSize: 2,
            datas: [],
            dataArr: [],
        };
    }
    // If you use redux, the data maybe at props, you need use `componentWillReceiveProps`
  componentWillReceiveProps(nextProps) {
    if (nextProps.dataSource !== this.props.dataSource) {
      this.setState({
        dataSource: this.state.dataSource.cloneWithRows(nextProps.dataSource),
      });
    }
  }
    componentDidUpdate() {
      
        if (this.state.useBodyScroll) {
            document.body.style.overflow = 'auto';
        } else {
            document.body.style.overflow = 'hidden';
        }
    }
    
    getData(ref = false) {
        let type = this.props.type
        let params = {
            data: {
                userId: 1,
                token: "asdhksjad"
            },
            type: type
        }
        const hei = this.state.height - ReactDOM.findDOMNode(this.lv).offsetTop;
        //获取数据
        var para = {}
        para.pageSize = this.state.pageSize
        para.pageNo = this.state.pageNo
        // console.log('子in',this.props.state.data);
        this.props.ContentAction(params).then(
            () => {
                const dataList = this.props.state.data
                console.log('里',this.props.state.data)
                let len
                if(dataList === undefined){
                    len= 0
                }else{
                 len = dataList.length
                }
                console.log(len)
                if (len <= 0) { // 判断是否已经没有数据了
                    this.setState({
                        refreshing: false,
                        isLoading: false,
                        hasMore: false,
                        height: hei,
                    })
                    Toast.info('没有数据了~', 1)
                    return false
                }
                if (ref) {
                    //这里表示刷新使用
                    // 下拉刷新的情况，重新添加数据即可(这里等于只直接用了第一页的数据)
                    this.setState({
                        pageNo: this.state.pageNo,
                        dataSource: this.state.dataSource.cloneWithRows(dataList), // 数据源中的数据本身是不可修改的,要更新datasource中的数据，请（每次都重新）调用cloneWithRows方法
                        hasMore: true, // 下拉刷新后，重新允许开下拉加载
                        refreshing: false, // 是否在刷新数据
                        isLoading: false, // 是否在加载中
                        dataArr: dataList // 保存数据进state，在下拉加载时需要使用已有数据
                    })
                } else {
                    // 这里表示上拉加载更多
                    // 合并state中已有的数据和新增的数据
                    var dataArr = this.state.dataArr.concat(dataList) //关键代码
                    this.setState({
                        pageNo: this.state.pageNo,
                        dataSource: this.state.dataSource.cloneWithRows(dataArr), // 数据源中的数据本身是不可修改的,要更新datasource中的数据，请（每次都重新）调用cloneWithRows方法
                        refreshing: false,
                        isLoading: false,
                        dataArr: dataArr // 保存新数据进state
                    })
                }
            }

        )
    }
    bindHandleScroll = (event) => {
        // console.log(event.target.scrollTop)
    }
    // componentWillUnmount() {
    //     window.removeEventListener('scroll', this.bindHandleScroll);
    // }
    componentDidMount = () => {
        // window.addEventListener('scroll', this.bindHandleScroll)
        const hei = this.state.height - ReactDOM.findDOMNode(this.lv).offsetTop;
        this.setState({
            height:hei
        })
        // this.props.state
        // window.scrollTo(0, 500);
        window.scrollBy(0, 100)
        this.getData(true)
    }
    onRefresh = () => {
     
        this.setState({
            refreshing: true,
            isLoading: true,
            pageNo: 1 // 刷新嘛，一般加载第一页，或者按你自己的逻辑（比如每次刷新，换一个随机页码）
        }, () => {
            this.getData(true)
        })
    };
    onEndReached = (event) => {
        if (this.state.isLoading && !this.state.hasMore) {
            return
        }
        this.setState({
            isLoading: true,
            pageNo: this.state.pageNo + 1, // 加载下一页
        }, () => {
            this.getData(false)
        })
    };
    render() {

        console.log(this.state.dataSource)
        const separator = (sectionID, rowID) => (
            <div
                key={`${sectionID}-${rowID}`}
                style={{
                    backgroundColor: '#F5F5F9',
                    height: 10,
                    // borderTop: '1px solid #ECECED',
                    // borderBottom: '1px solid #ECECED',
                }}
            />
        );
        const row = (rowData, sectionID, rowID) => {
            return (
                <div key={rowID} style={{ backgroundColor:'EFEFF4'}}>
                    {/* <div style={{height:'50px'}}>
                    <p>{rowData.articleName}</p>
                    </div> */}
                    <ContentCard contentData={rowData}/>
                </div>
            );
        };
        return (
        
            <div>
                <Button
                    style={{ margin: '30px 15px' }}
                    inline
                    onClick={() => this.setState({ useBodyScroll: !this.state.useBodyScroll })}
                >
                    {this.state.useBodyScroll ? 'useBodyScroll' : 'partial scroll'}
                </Button>
                <ListView
                    key={this.state.useBodyScroll ? '0' : '1'}
                    ref={el => this.lv = el}
                    dataSource={this.state.dataSource}
                    renderFooter={() => (<div style={{ padding: 30, textAlign: 'center' }}>
                        {this.state.isLoading ? 'Loading...' : 'Loaded'}
                    </div>)}
                    renderRow={row}
                    renderSeparator={separator}
                    useBodyScroll={this.state.useBodyScroll}
                    style={this.state.useBodyScroll ? {} : {
                        height: this.state.height,
                        border: '1px solid #ddd',
                        margin: '5px 0',
                    }}
                    pullToRefresh={<PullToRefresh
                        refreshing={this.state.refreshing}
                        onRefresh={this.onRefresh}
                    />}
                    onEndReached={this.onEndReached}
                    pageSize={1}
                    onScroll={this.bindHandleScroll}
                />
            </div>
        );
    }
}
const mapStateToProps = (state) => {
    return {
        state: state.content
    }
}
const actionCreator = { ContentAction }
export default connect(mapStateToProps, actionCreator)(TabbarBody);
